from lxml import etree
import requests
from concurrent.futures import ThreadPoolExecutor


file = open('./music.txt', 'w', encoding='utf-8')
tree = etree
headers = {
        "authority": "music.163.com",
        "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
        "accept-language": "zh-CN,zh;q=0.9",
        "cache-control": "no-cache",
        "pragma": "no-cache",
        "referer": "https://music.163.com/",
        "sec-ch-ua": "^\\^Chromium^^;v=^\\^118^^, ^\\^Microsoft",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "^\\^Windows^^",
        "sec-fetch-dest": "iframe",
        "sec-fetch-mode": "navigate",
        "sec-fetch-site": "same-origin",
        "sec-fetch-user": "?1",
        "upgrade-insecure-requests": "1",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36 Edg/118.0.2088.76"
    }
cookies = {
        "ntes_utid": "tid._.5rezjtssbqFEB1RBFVOU3tdFefD2Imit._.0"
    }
url = "https://music.163.com/discover/playlist/"

def download(offset):
    params = {
        "order": "hot",
        "cat": "^%^E5^%^85^%^A8^%^E9^%^83^%^A8",
        "limit": "35",
        "offset": str(offset)
    }
    resp = requests.get(url, headers=headers, cookies=cookies, params=params)

    if resp.status_code == 200:
        ree = tree.HTML(resp.text)
        href = ree.xpath('.//a[@class="msk"]/@href')
        tit = ree.xpath('.//a[@class="msk"]/@title')
        for num in range(len(href)):
            id = href[num].split('=')[-1]
            print(id, tit[num])
            file.write(id + '\t' + tit[num] + '\n')
    else:
        download(offset)
        print('爬取失败')

def main():
    offsets = [i * 35 for i in range(5)]
    with ThreadPoolExecutor(2) as pool:
        pool.map(download, offsets)

if __name__ == '__main__':
    main()